package com.sqkj.controller;

import com.sqkj.entity.Article;
import com.sqkj.service.ArticleService;
import com.sqkj.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RequestMapping("/upLoad")
@Controller
public class UpLoadController {
    @Resource
    ArticleService service;
    @Resource
    UserService userService;
    public static  final SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 记号,替换img标签
     */
    private static final String KUOHAO= "\\([a-zA-Z0-9]+\\.(jpg|gif|bmp|bnp|png|jpeg)\\)";
    private static final String SRC= "[a-zA-Z0-9]+\\.(jpg|gif|bmp|bnp|png|jpeg)";
    @RequestMapping("/upIndex")
    public String index() {
        return "upload";
    }
    @RequestMapping("/uploadText")
    public String uploadText() {
        return "uptext";
    }
    /**
     * 图片上传
     * @param request
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/uploadImg" ,method = RequestMethod.POST)
    public String FileUpload(HttpServletRequest request, Map<String,Object> map) throws Exception{
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        List<String> list = new ArrayList<String>();
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            list.add(file.getOriginalFilename());
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File("D:/upload/"+file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();

                } catch (Exception e) {
                    stream = null;
                    return "error";
                }
            } else {
                return "error ";
            }
        }

        map.put("fileNames", list);
        return "success";
    }
    /**
     * 上传文章信息
     * @param title,authorName,content
     * @param map
     * @return
     */
    @RequestMapping(value = "/uploadArtcle",method = RequestMethod.POST)
    public String addArtcle(String title , String authorName , String content, String headImg,String tag, Map<String ,Object> map){
        String headImgUrl = "http://localhost:8080/Path2/" + headImg;
        String articleAbstract = content.substring(0,45);
        Matcher matcher= Pattern.compile(SRC).matcher(content);
        Matcher matcher2= Pattern.compile(KUOHAO).matcher(content);
        List<String> list = new ArrayList<String>();
        while (matcher.find()){
            list.add(matcher.group());
        }
        int i = 0;
        while (matcher2.find()){
            content = content.replace(matcher2.group(),"<block><image class=\"head-image\" src=\"http://192.168.1.169:8080/Path2/"+list.get(i)+"\"></image></block>");
            i++;
        }
        content = content.replace("\r\n"," ");
        String dateStr = dateformat.format(System.currentTimeMillis());
        Article article =new Article(title,userService.findByName(authorName).get(0).getId(),0,dateStr,content,0,0,0,0,tag,articleAbstract,headImgUrl,"");
        service.add(article);
        return "index";
    }
     @RequestMapping("/text")
    public String uptext(String title , String authorName , String content) {
         String dateStr = dateformat.format(System.currentTimeMillis());
         Article article =new Article(title,userService.findByName(authorName).get(0).getId(),0,dateStr,content,0,0,0,0,"","","","");
         service.add(article);
         return "index";
    }
     @RequestMapping("/shanchu")
    public String delete(Map<String,Object> map) {
         String dateStr;
         List<Article> artcles = service.findAll();

         map.put("artcles", artcles);



         return "deletePage";
    }
     @RequestMapping("/deletePage")
    public String delete2(int id ) {
         service.deleteById(id);
         return "deleteSuccess";
    }
    @ResponseBody
    @RequestMapping(value = "/uploadUserIcon" ,method = RequestMethod.POST)
    public String FileUploadImg(HttpServletRequest request, Map<String,Object> map) throws Exception{
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        List<String> list = new ArrayList<String>();
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);

            if (!file.isEmpty()) {
                list.add(file.getOriginalFilename());
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File("D:/upload/userIcon/"+file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();

                } catch (Exception e) {
                    stream = null;

                    return e.getMessage();
                }
            } else {
                return "文件为空 ";
            }
        }

        map.put("fileNames", list);
        return "success";
    }
}
